package com.baseframe.mybatis.utils;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;



@AllArgsConstructor
public class BulkUtil {
    private SqlSessionFactory sqlSessionFactory;

    private  SqlSession getSqlSession(){

        return sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    }

    public <T> boolean insertBulk(Supplier<List<T>> supplier, Class<?extends BaseMapper<T>> baseMapperClass){
        try (SqlSession sqlSession = getSqlSession()) {
            BaseMapper<T> mapper = sqlSession.getMapper(baseMapperClass);
            HashSet<Boolean> hashSet = new HashSet<>();
            List<T> dataList = supplier.get();
            dataList.forEach(e -> {
                int insert = mapper.insert(e);
                hashSet.add(SqlHelper.retBool(insert));
            });

            if (hashSet.size() != 1) {
                sqlSession.rollback();
                return false;
            }
            sqlSession.commit();
            sqlSession.clearCache();

            return true;
        }

    }



}
